package com.fauks.ndk

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.widget.Toast
import com.fauks.ndk.databinding.ActivityNdkBasicBinding
import com.fauks.ndk.model.User

/*
* jni引用：局部引用newObject出了方法自动释放通过delelocal可以及时释放
* 全局引用，有些对象想要每个方法用需要提升为全局
* 弱全局引用，不会阻止回收，带来的问题是使用弱引用的时候可能被回收了
* */
class NDKBasicActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityNdkBasicBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.apply {
            btnTestNdkparam.setOnClickListener {
                ndkParams(intArrayOf(1, 2, 4), arrayOf("a", "b"))
                ndkParamsClass(User(), "fauks")
            }

            btnDynamic.setOnClickListener {
                testJavaDynamic()
                val result = testJavaDynamic2(1)
                btnTestNdkparam.text = "$result"
            }

            btnThread.setOnClickListener {
                testThread()
            }

            btnBuild.setOnClickListener {
                // testBuild()
            }

            btnMkStatic.setOnClickListener {
                val testMkStatic = testMkStatic()
                btnMkStatic.text = "result = $testMkStatic"
            }

            btnCmake.setOnClickListener {
                val result = testCmake()
                btnCmake.text = "result = $result"
            }
        }
    }

    // 测试ndk参数传递,java中所有的对象数组(String、自定义类)都会被映射成jobjectArray
    private external fun ndkParams(nums: IntArray, hobbys: Array<String>)

    // 传递java class
    private external fun ndkParamsClass(user: User, name: String)

    // jni动态注册
    private external fun testJavaDynamic()
    private external fun testJavaDynamic2(num: Int): Int

    // 线程
    private external fun testThread()

    // 交叉编译
    // private external fun testBuild()

    // mk 使用 静态库
    private external fun testMkStatic(): Int

    // 使用cmake
    private external fun testCmake(): Int

    fun updateUI() {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show()
        } else {
            runOnUiThread {
                Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show()
            }
        }
    }

    companion object {
        init {
            // 加载外部so库
            System.loadLibrary("Test")
            System.loadLibrary("ndk-test")
            // System.loadLibrary("mk-test")
        }
    }
}